package com.jiang.service.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jiang.dao.IMemberDao;
import com.jiang.dao.impl.MemberDaoImpl;
import com.jiang.factory.DaoFactory;
import com.jiang.service.IMemberService;
import com.jiang.vo.Member;

/**
 * @author Administrator
 *
 */
public class MemberServiceImpl implements IMemberService {

	/* (non-Javadoc)
	 * @see com.jiang.service.IMemberService#saveMemeber(com.jiang.vo.Member)
	 */
	@Override
	public boolean saveMemeber(Member member) throws SQLException {
		
		boolean result = false;
		// 这里是业务层的代码，实现数据校验, 然后出入到Dao层入库
		// 1.校验mid是否是邮箱或者手机号码 2. 校验是否已经存在该邮箱或者手机号码
		if(member!=null) {
			
			if(StringUtils.isNotBlank(member.getMid())){
				
				String mid = member.getMid();
				String reg_email = "^\\w+@\\w+\\.\\w+$";
				String reg_phone = "^(13)(\\d{9})|(15)(\\d{9})|(18)(\\d{9})$";
				if(mid.matches(reg_email) || mid.matches(reg_phone)) {
					// 校验是否已经存在过该主键
					IMemberDao memberDao = DaoFactory.getInstance(MemberDaoImpl.class);
					if(memberDao.findById(mid)!=null){
						System.out.println("请输入正确的mid, 此mid已经存在");
					}else{
						result = memberDao.doCreate(member);
					}
					
				}else{
					System.out.println("请输入正确的mid, 只能是邮箱或者手机号码!");
				}
				
			}else{
				System.out.println("mid不能为空");
			}
			
		}else{
			System.out.println("所传的参数member为空!");
		}
		
		return result;
	}

	@Override
	public List<Member> findAllMember() throws SQLException {
		
		IMemberDao memberDao = DaoFactory.getInstance(MemberDaoImpl.class);
		return memberDao.findAll();
	}

	@Override
	public boolean deleteBatch(List<Member> members) throws SQLException {

		IMemberDao memberDao = DaoFactory.getInstance(MemberDaoImpl.class);
		if(members.size()>0) {
			return memberDao.doBatchRemove(members); 
		}
		return false;
	}

	@Override
	public boolean update(Member member) throws SQLException {
		
		IMemberDao memberDao = DaoFactory.getInstance(MemberDaoImpl.class);
		if(member!=null) {
			return memberDao.doUpdate(member);
		}
		return false;
	}

	@Override
	public Member findMemberById(String mid) throws SQLException {

		IMemberDao memberDao = DaoFactory.getInstance(MemberDaoImpl.class);
		return memberDao.findById(mid);
	}

	
	
	@Override
	public Map<String, Object> findMemberSplit(String column, String keyWord, int currentPage, int pageSize) throws SQLException{

		IMemberDao memberDao = DaoFactory.getInstance(MemberDaoImpl.class);
		List<Member> members = memberDao.findSplit(column, keyWord, currentPage, pageSize);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", memberDao.findByKey(column, keyWord).size());
		map.put("members", members);
		return map;
	}


	
}
